<?php

namespace common\core\base;

use yii\helpers\ArrayHelper;

class RestAction extends \yii\base\Action
{
    use InvalidException;

    /**
     * @var string
     */
    protected $method;

    /**
     * @var string
     */
    public $data;

    /**
     * @var array
     */
    public $validateFiled;

    /**
     * @var array|null
     */
    public $filedDefault;

    public function runWithParams($params)
    {
        $data = [];
        switch ($this->method) {
            case 'get':
                $body = $params;
                break;
            case 'post';
                $body = \Yii::$app->request->post();
                break;
            case 'body';
                $body = \Yii::$app->request->getBodyParams();
                break;
            default:
                $body = [];
                break;
        }
        if (!empty($this->validateFiled)) {
            $data = $this->validateRequestParams($body, $this->validateFiled, $this->filedDefault);
        }

        if ($this->data instanceof \Closure) {
            $p = ArrayHelper::merge($data, $params);
            $row = call_user_func($this->data, $p);
        } else {
            $row = $this->data;
        }

        return $row;
    }
}